package month1;

public class PalindromeLinkedList234_04 {
    public static void main(String[] args) {
        System.out.println(isPalindrome(new ListNode(new int[]{1, 2, 4, 2, 1})));
    }
    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int[] arr) {
            ListNode tmp = this;
            for (int a : arr) {
                tmp.next = new ListNode(a);
                tmp = tmp.next;
            }
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    static boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        ListNode f = head.next, s = head;
        while(f != null && f.next != null) {
            f = f.next.next;
            s = s.next;
        }
        f = s.next;
        s.next = null;
        s = null;
        while(f != null) {
            ListNode p = f.next;
            f.next = s;
            s = f;
            f = p;
        }
        while(s != null && head != null) {
            if(s.val != head.val) {
                return false;
            }
            s = s.next;
            head = head.next;
        }
        return true;
    }
}
